package com.atguigu.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author xiaolong
 * @version 1.0
 * @description: TODO
 * @date 2021/10/7 14:25
 */
@RestController
@Slf4j
public class FlowLimitController {


    @GetMapping("/testA")
    public String testA() {
//        try {
//            TimeUnit.SECONDS.sleep(2);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "-----testA";
    }

    @GetMapping("/testB")
    public String testB() {
        log.info(Thread.currentThread().getName() + "\t" + "....testB");
        return "-----testB";
    }


    @GetMapping("/testD")
    public String testD() {
        try {
            //暂停几秒钟线程
            TimeUnit.SECONDS.sleep(1);
            log.info("testD 测试RT");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "-----testD";
    }

    @GetMapping("/testE")
    public String testE() {
        log.info("testE 测试异常数");
        int age = 10 / 0;
        return "-----testE 测试异常数";
    }


    /**
     * @param
     * @return
     * @description: SentinelResource  跟之前的HystrixCommand是差不多的
     */
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey")  //blockHandler若不满足sentinel热点key的要求就会去执行方法
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "------testHotKey";
    }

    /**
     * @param
     * @return
     * @description: 异常方法处理
     */
    public String deal_testHotKey(String p1, String p2, BlockException exception) {
        return "deal_testHotKey";  //sentinel系统默认的提示：Blocked by Sentinel（flow limiting）
    }

}
